/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.common.utils;

import cn.hutool.core.date.LocalDateTimeUtil;
import lombok.NonNull;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 数据辅助类
 * @author zpy
 * @version 1.0.0
 */
public final class DataUtils {
    public final static Integer SINGLE_COUNT = 1;

    private DataUtils(){}

    public static <T> T getFirst(List<T> data){
        return findFirst(data).orElse(null);
    }

    public static <T> String toString(T data){
        return toString(data,"");
    }

    public static <T> String toString(T data,String defaultValue){
        if(Objects.isNull(data)){
            return defaultValue;
        }
        return data.toString();
    }

    public static <T> Optional<T> findFirst(List<T> data){
        return data.stream()
                .findFirst();
    }


    /**
     * 比较时间是否在之前
     * @param date 时间
     * @param target 比较时间
     * @return 返回比较结果
     */
    public static boolean compareDateIsBefore(@NonNull LocalDateTime date, @NonNull LocalDateTime target){
        return date.isBefore(target);
    }

    public static long between(@NonNull LocalDate startDate, @NonNull LocalDate endDate, ChronoUnit unit){
        return LocalDateTimeUtil.between(startDate.atStartOfDay(),
                endDate.plusDays(1).atStartOfDay(),
                unit);
    }

    public static boolean range(@NonNull LocalDate date,@NonNull LocalDate start,@NonNull LocalDate end){
        return !date.isBefore(start) && !date.isAfter(end);
    }

}